﻿Option Strict On

Imports System.ComponentModel

Public Class GridLayoutPL
    Implements IReloadCommand, ISaveCommand, INewCommand

    Public Property Dataset As DataSet Implements ISaveCommand.Dataset
    Public WithEvents MetaDataTable As CommonExt.MetaDataTable
    Public WithEvents DetailView As Views.Grid.GridView

    'Use to hook Event when on LayoutView Mode
    Public WithEvents LayoutView As DevExpress.XtraGrid.Views.Layout.LayoutView
    'Use to know what index we are working on
    Public DetailViewIndex As Integer
    '''<remarks>
    '''When you define "Event InitDataExt" VB.NET automatically adds a field call InitDataExtEvent.
    '''The "InitDataExtEvent" will not show up in the IDE or Intellisense,
    '''however you are free to use it in your code
    '''</remarks>
    ''' 
    Public Event InitDataExt(ByVal grid As GridLayoutPL, ByVal withChild As Boolean)
    Public Event ValidateDataExt()
    Public Event ProcessDataExt()
    Public Event SaveDataExt()
    Public Event AfterSave()
    Public Event DeleteDataExt()
    Public Event DisplayExt(ByVal sender As GridView, ByVal aDataTable As DataTable) ' this is to extend the Display requirement of a Grid

    Public Event ValidateMasterRow(ByVal sender As Object, ByVal e As ValidateRowEventArgs)
    Public Event ValidateDetailRow(ByVal sender As Object, ByVal e As ValidateRowEventArgs)

    Public Event InitNewMasterRow(ByVal sender As Object, ByVal e As InitNewRowEventArgs)
    Public Event InitNewDetailRow(ByVal sender As Object, ByVal e As InitNewRowEventArgs)

    Public Event ShownMasterEditor(ByVal sender As Object, ByVal e As EventArgs)
    Public Event ShownDetailEditor(ByVal sender As Object, ByVal e As EventArgs)

    Public Event HiddenMasterEditor(ByVal sender As Object, ByVal e As EventArgs)
    Public Event HiddenDetailEditor(ByVal sender As Object, ByVal e As EventArgs)

    Public Event ProcessCurrentMasterRecord(ByVal sender As Object, e As ValidateRowEventArgs)
    Public Event ProcessCurrentDetailRecord(ByVal sender As Object, e As ValidateRowEventArgs, ByVal index As Integer)

    Public Event DeleteRow(ByVal row As DataRow, ByVal e As CancelEventArgs)

    Public Event MasterCellValueChanged(sender As Object, e As DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs)
    Public Event DetailCellValueChanged(sender As Object, e As DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs)

    Public Event MasterCustomColumnDisplayText(ByVal sender As Object, ByVal e As CustomColumnDisplayTextEventArgs)
    Public Event DetailCustomColumnDisplayText(ByVal sender As Object, ByVal e As CustomColumnDisplayTextEventArgs)

    Public Event MasterRowCellStyle(ByVal sender As Object, ByVal e As RowCellStyleEventArgs)
    Public Event DetailRowCellStyle(ByVal sender As Object, ByVal e As RowCellStyleEventArgs)

    Public Event MasterRowStyle(ByVal sender As Object, e As DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs)
    Public Event DetailRowStyle(ByVal sender As Object, e As DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs)

    Public Event MasterCustomRowCellEditForEditing(ByVal sender As System.Object, ByVal e As DevExpress.XtraGrid.Views.Grid.CustomRowCellEditEventArgs)
    Public Event DetailCustomRowCellEditForEditing(ByVal sender As System.Object, ByVal e As DevExpress.XtraGrid.Views.Grid.CustomRowCellEditEventArgs)

    Public Event DetailRowClick(ByVal sender As Object, ByVal e As RowClickEventArgs)
    Public Event MasterRowClick(ByVal sender As Object, ByVal e As RowClickEventArgs)

    Public Event AfterViewRegistered(ByVal sender As Object, ByVal e As DevExpress.XtraGrid.ViewOperationEventArgs)
    Public Event AfterLoad(ByVal sender As Object, ByVal e As System.EventArgs)

    Public Event MainContextMenuBeforePopup(ByVal sender As Object, ByVal e As System.EventArgs)

    Private timeEdit As RepositoryItemTimeEdit
    Private calcEdit As RepositoryItemCalcEdit
    Private memoEdit As RepositoryItemMemoEdit


    Private formatType As DevExpress.Utils.FormatType

    Public editorView As DataView
    Public AllowCreate As Boolean
    Public AllowRead As Boolean
    Public AllowUpdate As Boolean
    Public AllowDelete As Boolean

    Public DetailAccess As MetaQueryAccess = Nothing
    Public Property FormCtrlCD As String Implements IReloadCommand.CtrlName
    ''' <summary>
    ''' Use flag to determines if the grid should loads with or without his child's queries.
    ''' </summary>
    ''' <remarks>
    ''' Ex.: ItemMasterControl.vb line 217 - we want to show Site's info but not his child query like SiteSection. 
    ''' For now, this takes over the Security since the developper set this property manually.
    ''' Boolean: True by Default
    ''' </remarks>
    Public LoadWithChilds As Boolean = True

    'Pour le backgoudWorker - aleblanc - 2011-09-06
    'Reste les LOV a faire... 
    'Private waitWindow As DevExpress.Utils.WaitDialogForm
    'Private WithEvents bgWorker As System.ComponentModel.BackgroundWorker

#Region "Constructor"
    Public Sub New()
        ' This call is required by the designer.
        InitializeComponent()
        GridControl1.ForceInitialize()
        AddHandler GridControl1.EmbeddedNavigator.ButtonClick, AddressOf GridControl1_EmbeddedNavigator_ButtonClick
        '
        AllowCreate = True
        AllowRead = True
        AllowUpdate = True
        AllowDelete = True
        '
        timeEdit = New RepositoryItemTimeEdit()
        calcEdit = New RepositoryItemCalcEdit()
        memoEdit = New RepositoryItemMemoEdit()

        memoEdit.WordWrap = True

        Me.GridControl1.RepositoryItems.Add(timeEdit)
        Me.GridControl1.RepositoryItems.Add(calcEdit)
        Me.GridControl1.RepositoryItems.Add(memoEdit)

        Dataset = New DataSet("GridExtPL")
        ' Add any initialization after the InitializeComponent() call.
        InitActionOption()

        ' Pour le backgoudWorker - aleblanc - 2011-09-06
        'bgWorker = New System.ComponentModel.BackgroundWorker()
        'bgWorker.WorkerReportsProgress = False
        'bgWorker.WorkerSupportsCancellation = False
    End Sub

    'Public Sub New(ByVal aQueryName As String)
    '    Me.New()
    '    MainQueryName = aQueryName
    '    ' Add any initialization after the InitializeComponent() call.
    '    InitGridExt()
    'End Sub
#End Region

#Region " Properties"
    Public ReadOnly Property ParentSelectedDataRow() As DataRow
        Get
            Dim view As Views.Grid.GridView = CType(GridControl1.FocusedView.ParentView, Views.Grid.GridView)
            Return view.GetFocusedDataRow
        End Get
    End Property

    Public Property Pl() As PL.PLBase

    Public Property GridActionOptionList() As CommonExt.Base.ActionOptionList

    Public Property DefaultActionOptionList() As CommonExt.Base.ActionOptionList

    Public Property GridContextMenu() As GridViewMenu

    Public Property MainQueryName() As String
#End Region
    ''' <summary>
    ''' Use to Flag if displayed columns are according to the security profile
    ''' </summary>
    ''' <returns>Boolean: False by Default</returns>
    ''' <remarks></remarks>
    Public Property SecureGrid() As Boolean = False

    Public Sub InitGridExt(Optional ByVal withChild As Boolean = True)
        Dim mainViewAccess As MetaQueryAccess = Nothing
        Dim mqCtrlName As String = Nothing
        ' Pour le backgoudWorker - aleblanc - 2011-09-06
        GridControl1.BeginUpdate()
        If Not String.IsNullOrWhiteSpace(FormCtrlCD) Then
            Me.AllowRead = False
            Me.AllowUpdate = False
            Me.AllowDelete = False
            Me.AllowCreate = False
            If Pl IsNot Nothing Then
                mqCtrlName = AppManager.GetControlMqFromForm(FormCtrlCD, Pl.QueryName)
                If Not String.IsNullOrWhiteSpace(mqCtrlName) Then
                    mainViewAccess = New MetaQueryAccess(mqCtrlName)
                    If mainViewAccess IsNot Nothing Then
                        Me.AllowRead = CBool(mainViewAccess.AllowRead)
                        Me.AllowUpdate = mainViewAccess.AllowUpdate
                        Me.AllowDelete = mainViewAccess.AllowDelete
                        Me.AllowCreate = mainViewAccess.AllowCreate
                    End If
                End If
            End If
        End If
        If AllowRead Then
            If Pl IsNot Nothing Then
                Pl.InitData(withChild)
                Me.Dataset = Pl.Dataset
            Else
                RaiseEvent InitDataExt(Me, withChild) ' This event can be used to bypass the use of a Processing Layer object(PL)
            End If
        End If

        InitGrid()
        GridControl1.EndUpdate()
    End Sub

    'Basé sur l'exemple de http://www.devexpress.com/Support/Center/e/E1127.aspx
    Private Sub GridControl1_EmbeddedNavigator_ButtonClick(ByVal sender As Object, ByVal e As NavigatorButtonClickEventArgs)
        If e.Button.ButtonType = NavigatorButtonType.Remove Then
            DeleteCurrentRows()
            'TestPoint: Si on enleve cette ligne ca continue l'événement et va delete l'autre ligne en focus (2 lignes) - aleblanc 2011-10-07.
            e.Handled = True
        End If
    End Sub
    ''' <summary>
    ''' This Sub initialise the GridExt 
    ''' </summary>
    ''' <remarks>La grille essaye toujours d'avoir les enfants (by design)
    ''' a) creates a Dataset , the Table(0) is the Parent
    ''' b) </remarks>
    Private Sub InitGrid()
        Dim metaDt As MetaDataTable
        Dim relationName As String
        Dim parentRelation As String
        Dim queryName As String
        Dim level As Integer
        '
        Try
            GridControl1.LevelTree.Nodes.Clear()

            If Dataset IsNot Nothing AndAlso Dataset.Tables.Count > 0 Then
                MainQueryName = Dataset.Tables(0).TableName
                'Ici on se sert du parent de notre dataset
                'Par convention la table 0 de notre DataSet est le parent de nos relation
                MetaDataTable = CType(Dataset.Tables(0), MetaDataTable)
                GridControl1.DataSource = Dataset.Tables(0)
                InitMainView()
                'Ici on parcours les tables a afficher
                If LoadWithChilds Then
                    For Each row As DataRow In MetaDataTable.MetaCommand.GetChildDisplayQuery.Rows
                        metaDt = CType(Dataset.Tables(row("QueryName").ToString), MetaDataTable)
                        parentRelation = row("ParentRelation").ToString
                        relationName = row("Relation").ToString
                        queryName = row("Relation").ToString
                        level = CInt(row("MetaqueryLevel"))
                        InitAndLinkDetailViewProperty(parentRelation, relationName, metaDt, level)
                    Next
                End If
            End If
        Catch ex As Exception
            MessageWindow.ShowMessage(ex, MsgBoxStyle.Information)
        End Try
    End Sub


    Private Sub InitAndLinkDetailViewProperty(ByVal parentRelation As String, ByVal relationName As String, ByVal table As MetaDataTable, ByVal level As Integer)
        Dim aDetailView As GridView = New GridView(GridControl1)
        Dim column As GridColumn
        Dim colVisible As Boolean
        Dim grdLvLNode As GridLevelNode
        Dim tmpLvLNode As GridLevelNode
        Dim tableColumns As DataTable
        Dim colname As String
        '
        aDetailView.Name = relationName
        If level = 1 Then
            GridControl1.LevelTree.Nodes.Add(relationName, aDetailView)
        Else
            If GridControl1.LevelTree.Nodes.Contains(parentRelation) Then
                'GridControl1.LevelTree.Nodes(parentRelation).Nodes.Add(relationName, aDetailView)
                grdLvLNode = GridControl1.LevelTree.Nodes.Item(parentRelation)
                tmpLvLNode = grdLvLNode.Nodes.Add(relationName, aDetailView)
            End If
        End If
        '
        ' On le force a false car quand on a des cellule de mergé le Row Selector disparait
        aDetailView.OptionsView.AllowCellMerge = False

        aDetailView.OptionsView.ShowFooter = False


        'Le tag est utilisé pour se retrouvé dans dans les événements plus loin
        'ByDesign c'est le nom de la metaquery.
        aDetailView.Tag = table.TableName
        aDetailView.PopulateColumns(table)
        '
        '
        'Ici on CTYPE relation.ChildTable car un DataRelation (un type du Framework de MS) contient des DataTable, 
        'comme notre MetaDataTable hérite d'un DataTable il est compatible

        If SecureGrid Then
            tableColumns = CommonExt.Base.AppManager.GetUserColumnSecurity(table.TableName, CommonExt.Base.AppManager.UserID)
        Else
            tableColumns = table.MetaData
        End If

        tableColumns.TableName = table.TableName

        For Each arow As DataRow In tableColumns.Rows
            colname = arow("ColumnName").ToString
            colVisible = CBool(IIf(CInt(arow("pVisible")) = 0, False, True))
            column = aDetailView.Columns(colname)
            If column IsNot Nothing Then
                column.VisibleIndex = CInt(arow("pOrder"))
                column.Caption = arow("pCaption").ToString
                column.Visible = colVisible
                column.Width = CInt(arow("pWidth"))
                column.OptionsColumn.AllowEdit = Not CBool(arow("pLocked"))

                If Not String.IsNullOrEmpty(Trim(arow("pBackColor").ToString)) Then
                    column.AppearanceCell.BackColor = ColorTranslator.FromOle(Math.Abs(CInt(arow("pBackColor"))))
                End If

                If CBool(arow("pMerge")) Then
                    aDetailView.OptionsView.AllowCellMerge = True
                    column.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.True
                Else
                    column.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False
                End If
                '
                If CInt(arow("pGroupByOrder")) > 0 Then
                    column.GroupIndex = CInt(arow("pGroupByOrder"))
                End If
                '
                column.ToolTip = arow("pToolTip").ToString
                '
                formatType = DevExGridHelper.GetFormatType(arow)
                If formatType = DevExpress.Utils.FormatType.DateTime Then
                    timeEdit.DisplayFormat.FormatType = formatType
                    timeEdit.DisplayFormat.FormatString = arow("pNumberFormat").ToString
                    timeEdit.EditFormat.FormatType = formatType
                    timeEdit.EditFormat.FormatString = arow("pNumberFormat").ToString
                    timeEdit.EditMask = arow("pNumberFormat").ToString
                    column.ColumnEdit = timeEdit
                End If
                '
                If formatType = DevExpress.Utils.FormatType.Numeric Then
                    calcEdit.EditFormat.FormatType = DevExpress.Utils.FormatType.Numeric
                    calcEdit.EditFormat.FormatString = arow("pNumberFormat").ToString()
                    calcEdit.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric
                    calcEdit.DisplayFormat.FormatString = arow("pNumberFormat").ToString()
                    column.ColumnEdit = calcEdit
                End If
                '
                If Not IsDBNull(arow("pNumberFormatID_FK")) Then
                    If CType(arow("pNumberFormatID_FK"), Guid) = IdRepository.META_NUMBERFORMAT_EXTERNALEDITOR Then
                        column.ColumnEdit = memoEdit
                    End If
                End If
                '
                column.DisplayFormat.FormatType = formatType
                column.DisplayFormat.FormatString = arow("pNumberFormat").ToString
                '
                column.SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.None
                DevExGridHelper.AssignCustomSummaryProperties(aDetailView, column, arow)
            Else
                Throw New Exception(String.Format("MetaColumn: [{0}], Not found in MetaQuery.SqlStatement [{1}] (Case-sensitive)", colname, table.TableName))
            End If
        Next

        'Grid Display parameters
        'This could all be define in Metacontrol Props
        aDetailView.HorzScrollVisibility = Views.Base.ScrollVisibility.Always
        aDetailView.OptionsDetail.EnableDetailToolTip = True
        aDetailView.OptionsDetail.AllowExpandEmptyDetails = True
        '
        aDetailView.OptionsFilter.DefaultFilterEditorView = FilterEditorViewMode.VisualAndText
        aDetailView.OptionsFilter.ShowAllTableValuesInFilterPopup = True
        aDetailView.OptionsFilter.UseNewCustomFilterDialog = True
        '
        aDetailView.OptionsView.ColumnAutoWidth = False
        aDetailView.OptionsView.NewItemRowPosition = NewItemRowPosition.Top
        aDetailView.OptionsView.ShowAutoFilterRow = True
        aDetailView.OptionsView.ShowChildrenInGroupPanel = True
        aDetailView.OptionsView.ShowFilterPanelMode = Views.Base.ShowFilterPanelMode.ShowAlways
        '
        'Le nom de l'onglet de la vue
        'aView.OptionsView.ShowViewCaption = True 'Permet d'afficher le nom du Caption dans une ligne en haut du Grid
        aDetailView.ViewCaption = table.MetaCommand.Caption

        'Necessaire pour les memoedit
        aDetailView.OptionsView.RowAutoHeight = True

        aDetailView.OptionsSelection.MultiSelect = True
        aDetailView.OptionsBehavior.EditorShowMode = DevExpress.Utils.EditorShowMode.MouseUp
        ''Make sure that the columns are define in the view before assignning LOV'S
        DevExGridHelper.AssignLKP(aDetailView, table, Me.GridControl1)
        tableColumns.Dispose()
    End Sub
    ''' <summary>
    ''' Initialise la grille parents
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub InitMainView()
        Dim colVisible As Boolean
        Dim mainView As Views.Base.ColumnView = CType(GridControl1.MainView, Views.Base.ColumnView)
        Dim column As DevExpress.XtraGrid.Columns.GridColumn
        Dim tableColumns As DataTable
        Dim colname As String

        'This action is mandaotry due to the fact that as soon as Grid control datasource is set
        'the columns view are loaded but not specified the application requires
        mainView.Columns.Clear()

        ' On le force a false car quand on a des cellule de mergé le Row Selector disparait
        GridView1.OptionsView.AllowCellMerge = False
        '
        If SecureGrid Then
            tableColumns = CommonExt.Base.AppManager.GetUserColumnSecurity(MetaDataTable.TableName, CommonExt.Base.AppManager.UserID)
        Else
            tableColumns = MetaDataTable.MetaData
        End If
        '
        Me.MetaDataTable.DefaultView.AllowEdit = Me.AllowUpdate
        Me.MetaDataTable.DefaultView.AllowDelete = Me.AllowDelete
        Me.MetaDataTable.DefaultView.AllowNew = Me.AllowCreate
        '
        For Each row As DataRow In tableColumns.Rows
            colname = row("ColumnName").ToString
            colVisible = CBool(IIf(CInt(row("pVisible")) = 0, False, True))
            column = mainView.Columns.AddField(colname)
            column.VisibleIndex = CInt(row("pOrder"))
            column.Caption = row("pCaption").ToString
            column.Visible = colVisible
            column.Width = CInt(row("pWidth"))
            column.OptionsColumn.AllowEdit = Not CBool(row("pLocked"))
            column.ToolTip = row("pToolTip").ToString

            If Not String.IsNullOrEmpty(Trim(row("pBackColor").ToString)) Then
                column.AppearanceCell.BackColor = ColorTranslator.FromOle(Math.Abs(CInt(row("pBackColor"))))
            End If

            If CBool(row("pMerge")) Then
                GridView1.OptionsView.AllowCellMerge = True
                column.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.True
            Else
                column.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False
            End If

            If CInt(row("pGroupByOrder")) > 0 Then
                column.GroupIndex = CInt(row("pGroupByOrder"))
                column.SortIndex = CInt(row("pGroupByOrder"))
                column.SortOrder = DevExpress.Data.ColumnSortOrder.Ascending
                column.SortMode = ColumnSortMode.DisplayText

            End If
            '
            formatType = DevExGridHelper.GetFormatType(row)
            If formatType = DevExpress.Utils.FormatType.DateTime Then
                timeEdit.DisplayFormat.FormatType = formatType
                timeEdit.DisplayFormat.FormatString = row("pNumberFormat").ToString
                timeEdit.EditFormat.FormatType = formatType
                timeEdit.EditFormat.FormatString = row("pNumberFormat").ToString
                timeEdit.EditMask = row("pNumberFormat").ToString
                column.ColumnEdit = timeEdit
            End If
            '
            If formatType = DevExpress.Utils.FormatType.Numeric Then
                calcEdit.EditFormat.FormatType = DevExpress.Utils.FormatType.Numeric
                calcEdit.EditFormat.FormatString = row("pNumberFormat").ToString()
                calcEdit.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric
                calcEdit.DisplayFormat.FormatString = row("pNumberFormat").ToString()
                column.ColumnEdit = calcEdit
            End If
            If Not IsDBNull(row("pNumberFormatID_FK")) Then
                If CType(row("pNumberFormatID_FK"), Guid) = IdRepository.META_NUMBERFORMAT_EXTERNALEDITOR Then
                    column.ColumnEdit = memoEdit
                End If
            End If
            '
            column.DisplayFormat.FormatType = formatType
            column.DisplayFormat.FormatString = row("pNumberFormat").ToString
            '
            DevExGridHelper.AssignCustomSummaryProperties(GridView1, column, row)
        Next

        GridView1.GridControl = Me.GridControl1
        GridView1.Name = "ParentView"
        GridView1.Tag = MetaDataTable.TableName
        GridView1.HorzScrollVisibility = Views.Base.ScrollVisibility.Always
        '
        GridView1.OptionsDetail.AllowExpandEmptyDetails = True
        GridView1.OptionsDetail.EnableDetailToolTip = True
        '
        GridView1.OptionsFilter.DefaultFilterEditorView = FilterEditorViewMode.VisualAndText
        GridView1.OptionsFilter.ShowAllTableValuesInFilterPopup = True
        GridView1.OptionsFilter.UseNewCustomFilterDialog = True
        '
        If Me.AllowCreate Then
            GridView1.OptionsView.NewItemRowPosition = NewItemRowPosition.Top
        Else
            GridView1.OptionsView.NewItemRowPosition = NewItemRowPosition.None
        End If
        '
        GridView1.OptionsView.ShowAutoFilterRow = True
        GridView1.OptionsView.ShowChildrenInGroupPanel = True
        GridView1.OptionsView.ShowFilterPanelMode = Views.Base.ShowFilterPanelMode.ShowAlways

        'Necessaire pour les memoedit
        GridView1.OptionsView.RowAutoHeight = True

        'Le nom de l'onglet de la vue
        'GridView1.OptionsView.ShowViewCaption = True   'Permet d'afficher le nom du Caption dans une ligne en haut du Grid
        GridView1.ViewCaption = MetaDataTable.MetaCommand.Caption
        'Make sure that the columns are define in the view before assignning LOV'S
        DevExGridHelper.AssignLKP(CType(mainView, LayoutView), MetaDataTable, Me.GridControl1)
        RaiseEvent DisplayExt(GridView1, tableColumns)
        tableColumns.Dispose()
    End Sub
    Private Sub GridView1_CellValueChanged(sender As Object, e As DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs) Handles LayoutView1.CellValueChanged
        If MasterCellValueChangedEvent IsNot Nothing Then
            RaiseEvent MasterCellValueChanged(sender, e)
        End If
    End Sub
    Private Sub GridView1_InitNewRow(ByVal sender As Object, ByVal e As InitNewRowEventArgs) Handles LayoutView1.InitNewRow
        If InitNewMasterRowEvent Is Nothing Then
            Dim view As GridView = CType(sender, GridView)
            view.SetRowCellValue(e.RowHandle, view.Columns(MetaDataTable.MetaCommand.GUIDField), System.Guid.NewGuid)
        Else
            RaiseEvent InitNewMasterRow(sender, e)
        End If
    End Sub

    Private Sub DetailView_CellValueChanged(sender As Object, e As DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs) Handles DetailView.CellValueChanged
        If DetailCellValueChangedEvent IsNot Nothing Then
            RaiseEvent DetailCellValueChanged(sender, e)
        End If
    End Sub
    Private Sub DetailView_InitNewRow(ByVal sender As Object, ByVal e As InitNewRowEventArgs) Handles DetailView.InitNewRow
        If InitNewDetailRowEvent Is Nothing Then
            Dim view As GridView = CType(sender, GridView)
            Dim drow As DataRow = view.GetFocusedDataRow()
            Dim table As MetaDataTable = CType(drow.Table, MetaDataTable)
            view.SetRowCellValue(e.RowHandle, view.Columns(table.MetaCommand.GUIDField), System.Guid.NewGuid)
        Else
            RaiseEvent InitNewDetailRow(sender, e)
        End If
    End Sub

    Public Function SaveCommand() As Boolean Implements CommonExt.ISaveCommand.SaveCommand
        Dim succesful As Boolean = True
        Try
            Me.Cursor = Cursors.WaitCursor
            'On force la fermeture de l'éditeur.
            GridControl1.FocusedView.CloseEditor()
            GridControl1.FocusedView.UpdateCurrentRow()
            '
            Me.Refresh()
            If Not Me.Dataset.HasErrors Then
                If Pl IsNot Nothing Then
                    succesful = Pl.Save()
                    GridControl1.RefreshDataSource()
                Else
                    'OutStandingIssue: Il faut trouver comment ce passer des résultats avec les events - aleblanc 
                    RaiseEvent ValidateDataExt()
                    'Si valide on peut Processer
                    RaiseEvent ProcessDataExt()
                    'Si le process a marcher on peut Sauver
                    RaiseEvent SaveDataExt()
                End If

                'Une fois sauver on avertie que le save a marcher
                If succesful Then
                    RaiseEvent AfterSave()
                End If
            Else
                succesful = False
            End If
        Catch ex As Exception
            MessageWindow.ShowMessage(ex, MsgBoxStyle.Information)
        Finally
            Me.Cursor = Cursors.Default
        End Try
        Return succesful
    End Function



    Private Sub GridControl1_FocusedViewChanged(sender As Object, e As ViewFocusEventArgs) Handles GridControl1.FocusedViewChanged
        If Not IsNothing(e.View) Then ' this is required because of event is fired on form closing and View's are Nothing, at run time it raise an error.. why event is fired ... we don't know  -B.desjardins
            If TypeOf (GridControl1.FocusedView) Is GridView Then
                If DirectCast(e.View, DevExpress.XtraGrid.Views.Grid.GridView).IsDetailView Then
                    DetailView = DirectCast(GridControl1.FocusedView, GridView)
                End If
            ElseIf TypeOf (GridControl1.FocusedView) Is Views.Layout.LayoutView Then
                LayoutView = DirectCast(GridControl1.FocusedView, Views.Layout.LayoutView)
            End If
        End If

        'Refactoring Child: 8- Prendre le DataSource de la DetailView et le passer au DirectCast(xx,MetaDataTable).FillBusinessApplicationData()
        'Exemple:
        'Dim mt As MetaDataTable
        'mt = TryCast(DetailView.DataSource, MetaDataTable)
        'If mt Is Nothing Then
        '    mt.FillBusinessApplicationData()
        'End If
    End Sub

    ''' <summary>
    ''' Delete the FocusedRow - Delete key
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks>KeyUp does not raise when editing a Cell/Row</remarks>
    Private Sub GridControl1_KeyUp(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles GridControl1.KeyUp
        If e.KeyCode = Keys.Delete AndAlso Not e.Control Then
            DeleteCurrentRows()
        End If
    End Sub

    Private Sub GridControl1_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles GridControl1.MouseClick
        Dim point As Point
        Dim hi As DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo

        If e.Button = MouseButtons.Right Then
            ' checking if the end-user has right clicked the grid control 
            point = New Point(e.X, e.Y)
            hi = TryCast(GridControl1.FocusedView.CalcHitInfo(point), Grid.ViewInfo.GridHitInfo)

            If Not IsNothing(hi) AndAlso hi.HitTest = Grid.ViewInfo.GridHitTest.RowIndicator Then
                If GridControl1.FocusedView.IsDetailView Then
                    DoShowDetailViewMenu(hi)
                Else
                    DoShowMainViewMenu(hi)
                End If
            End If
        End If
    End Sub
    Private Sub DoShowDetailViewMenu(ByVal hi As DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo)
        Dim item As DXMenuItem
        Dim dtlView As GridView = CType(GridControl1.FocusedView, GridView)
        Dim grpName As String = String.Empty
        Dim selectedRows As GridSelectedRows = New GridSelectedRows()

        GridContextMenu = New GridViewMenu(dtlView)
        If GridActionOptionList IsNot Nothing Then
            For Each action As CommonExt.Base.ActionOption In DefaultActionOptionList
                item = New DXMenuItem(action.OptionTitle, action.EventHandler, Nothing)
                Select Case action.OptionName
                    Case "ZoomIn"
                        item.Enabled = GridControl1.FocusedView.IsDetailView And Not GridControl1.FocusedView.IsZoomedView
                    Case "ZoomOut"
                        item.Enabled = GridControl1.FocusedView.IsDetailView And GridControl1.FocusedView.IsZoomedView
                    Case Else
                        item.Enabled = True
                End Select
                'Add new Group Separator when Group Name change
                If (grpName <> action.OptionGroup And grpName <> String.Empty) Then
                    item.BeginGroup = True
                End If
                grpName = action.OptionGroup
                GridContextMenu.Items.Add(item)
            Next
            'Add Action Option that need the grid DataRow
            For Each action As CommonExt.Base.ActionOption In Me.GridActionOptionList
                item = New DXMenuItem(action.OptionTitle, action.EventHandler, Nothing)

                selectedRows.CurrentSelectedDataRow = dtlView.GetFocusedDataRow()
                selectedRows.ParentSelectedDataRow = ParentSelectedDataRow

                'item.Tag = dtlView.GetFocusedDataRow()
                item.Tag = selectedRows

                item.Enabled = action.Enabled
                'item.Image = action.OptionIcon
                If item.Tag Is Nothing Then
                    item.Enabled = False
                End If
                'Add new Group Separator when Group Name change
                If (grpName <> action.OptionGroup And grpName <> String.Empty) Then
                    item.BeginGroup = True
                End If
                grpName = action.OptionGroup
                If action.IndentLevelReference = dtlView.Tag.ToString Then
                    GridContextMenu.Items.Add(item)
                End If
            Next
            'Display Menu
            GridContextMenu.Show(hi.HitPoint)
        End If
    End Sub
    Sub DoShowMainViewMenu(ByVal hi As DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo)
        Dim item As DXMenuItem
        Dim grpName As String = String.Empty

        GridContextMenu = New GridViewMenu(GridView1)
        AddHandler GridContextMenu.BeforePopup, AddressOf MainViewContextMenu_BeforePopup
        If GridActionOptionList IsNot Nothing Then
            For Each action As CommonExt.Base.ActionOption In DefaultActionOptionList
                item = New DXMenuItem(action.OptionTitle, action.EventHandler, Nothing)
                item.Enabled = action.Enabled
                'Add new Group Separator when Group Name change
                If (grpName <> action.OptionGroup And grpName <> String.Empty) Then
                    item.BeginGroup = True
                End If
                grpName = action.OptionGroup
                GridContextMenu.Items.Add(item)
            Next
            'Add Action Option that need the grid DataRow
            For Each action As CommonExt.Base.ActionOption In Me.GridActionOptionList
                item = New DXMenuItem(action.OptionTitle, action.EventHandler, Nothing)
                item.Tag = GridView1.GetFocusedDataRow()
                item.Enabled = action.Enabled
                'item.Image = action.OptionIcon
                If item.Tag Is Nothing Then
                    item.Enabled = False
                End If
                'Add new Group Separator when Group Name change
                If (grpName <> action.OptionGroup And grpName <> String.Empty) Then
                    item.BeginGroup = True
                End If
                grpName = action.OptionGroup
                If String.IsNullOrEmpty(action.IndentLevelReference) OrElse action.IndentLevelReference = GridView1.Tag.ToString Then
                    GridContextMenu.Items.Add(item)
                End If
            Next
            'Display Menu
            GridContextMenu.Show(hi.HitPoint)
        End If
    End Sub
    Private Sub GridExtPL_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        InitGridExt(LoadWithChilds)

        If AfterLoadEvent IsNot Nothing Then
            RaiseEvent AfterLoad(sender, e)
            If Me.AllowCreate Then
                GridView1.OptionsView.NewItemRowPosition = NewItemRowPosition.Top
            Else
                GridView1.OptionsView.NewItemRowPosition = NewItemRowPosition.None
            End If
        End If
    End Sub
#Region " Context Action Menu"
    Private Sub InitActionOption()
        Dim act As CommonExt.Base.ActionOption
        GridActionOptionList = New CommonExt.Base.ActionOptionList()
        DefaultActionOptionList = New CommonExt.Base.ActionOptionList()

        act = New CommonExt.Base.ActionOption("GridOption", "Refresh", "Refresh Data", AddressOf ContextMenuReloadGrid, True, True)
        DefaultActionOptionList.Add(act)

        act = New CommonExt.Base.ActionOption("GridOption", "ToExcel", "Export to Excel", AddressOf ContextMenuExportToExcel, True, True)
        DefaultActionOptionList.Add(act)

        act = New CommonExt.Base.ActionOption("GridOption", "LayoutView", "Layout View", AddressOf ContextMenuLayoutView, True, True)
        DefaultActionOptionList.Add(act)

        act = New CommonExt.Base.ActionOption("DefaultOption", "SaveData", "Save", AddressOf ContextMenuSave, True, True)
        DefaultActionOptionList.Add(act)

        act = New CommonExt.Base.ActionOption("DefaultOption", "DeleteData", "Delete", AddressOf ContextMenuDelete, True, True)
        DefaultActionOptionList.Add(act)

        act = New CommonExt.Base.ActionOption("DefaultOptionZ", "ZoomIn", "Zoom In", AddressOf ContextMenuZoomIn, False, True)
        DefaultActionOptionList.Add(act)
        act = New CommonExt.Base.ActionOption("DefaultOptionZ", "ZoomOut", "Zoom Out", AddressOf ContextMenuZoomOut, False, True)
        DefaultActionOptionList.Add(act)
    End Sub
    Private Sub ContextMenuSave(ByVal sender As System.Object, ByVal e As EventArgs)
        Me.SaveCommand()
    End Sub
    Private Sub ContextMenuDelete(ByVal sender As System.Object, ByVal e As EventArgs)
        DeleteCurrentRows()
    End Sub
    Private Sub DeleteCurrentRows()
        Dim view As LayoutView = CType(Me.GridControl1.FocusedView, LayoutView)

        Dim okdelete As Boolean = Me.AllowDelete

        If view.IsDetailView Then
            If DetailAccess IsNot Nothing Then
                okdelete = DetailAccess.AllowDelete
            End If
        End If

        If okdelete Then
            If DeleteRowEvent Is Nothing Then
                view.DeleteSelectedRows()
            Else
                Dim cnclEvent As New CancelEventArgs(False)
                RaiseEvent DeleteRow(view.GetFocusedDataRow, cnclEvent)
                If Not cnclEvent.Cancel Then
                    view.DeleteSelectedRows()
                End If
            End If
        Else
            MessageWindow.ShowMessage("You do not have rights to delete row", MsgBoxStyle.Information)
        End If
    End Sub
    Private Sub ContextMenuLayoutView(ByVal sender As System.Object, ByVal e As EventArgs)
        ChangeView(GridControl1, GridControl1.LevelTree, "LayoutView", False)
    End Sub
    Private Sub ContextMenuExportToExcel(ByVal sender As System.Object, ByVal e As EventArgs)

        'OutStandingIssue: On ne peut pas exporter la vue detail seulement... Il faut passerpar la Vue principal.
        'Work Around: Reconstruire une grille avec la table dataSet via le FocusedView.Tag.ToString (Comme ContextMenuVEdit) et appliquer un filtre apartir du la Row Parent.
        'aleblanc - 2011-07-26
        'http://www.devexpress.com/Support/Center/p/S130097.aspx.  C'est pareil pour les XLS
        '
        Dim filename As String
        Try
            filename = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), GridView1.Tag.ToString + ".xls")

            GridView1.OptionsPrint.AutoWidth = False
            GridView1.OptionsPrint.PrintDetails = True
            GridView1.OptionsPrint.ExpandAllDetails = True
            GridView1.OptionsPrint.ExpandAllGroups = True
            GridView1.ExportToXls(filename)

            MessageWindow.ShowMessage(String.Format("Export To Excel Succesfull.{0}{0}Your Filename is: {1}", vbCrLf, filename), MsgBoxStyle.Information)

        Catch ex As Exception
            Throw ex
        End Try
        Me.Cursor = Cursors.Default
    End Sub
    Private Sub ContextMenuReloadGrid(ByVal sender As System.Object, ByVal e As EventArgs)
        ReloadGrid()
    End Sub
#End Region
    Public Sub ReloadGrid()
        Me.Cursor = Cursors.WaitCursor
        GridControl1.DataSource = Nothing
        '
        'On enleve les LOV et les editeurs de la grilles
        'Car pour les LOV on réutilise les colonnes qui on déjà le même LOV
        GridControl1.RepositoryItems.Clear()
        '
        InitGridExt(LoadWithChilds)
        Me.Cursor = Cursors.Default
    End Sub
    Private Sub ContextMenuZoomIn(ByVal sender As System.Object, ByVal e As EventArgs)
        GridControl1.FocusedView.ZoomView()
    End Sub
    Private Sub ContextMenuZoomOut(ByVal sender As System.Object, ByVal e As EventArgs)
        GridControl1.FocusedView.NormalView()
    End Sub
    'Private Sub _aview_MasterRowExpanded(sender As Object, e As DevExpress.XtraGrid.Views.Grid.CustomMasterRowEventArgs) Handles _aview.MasterRowExpanded
    '    Dim chldView As DevExpress.XtraGrid.Views.Grid.GridView = CType(GridControl1.FocusedView, DevExpress.XtraGrid.Views.Grid.GridView)
    '    Dim row As Integer = chldView.FocusedRowHandle

    '    _aview = CType(chldView.GetDetailView(row, e.RelationIndex), DevExpress.XtraGrid.Views.Grid.GridView)
    'End Sub
    Private Sub DetailView_ShownEditor(sender As Object, e As System.EventArgs) Handles DetailView.ShownEditor
        RaiseEvent ShownDetailEditor(sender, e)
    End Sub
    Private Sub GridView1_ShownEditor(sender As Object, e As System.EventArgs) Handles GridView1.ShownEditor
        RaiseEvent ShownMasterEditor(sender, e)
    End Sub
    Private Sub DetailView_HiddenEditor(sender As Object, e As System.EventArgs) Handles DetailView.HiddenEditor
        RaiseEvent HiddenDetailEditor(sender, e)
    End Sub
    Private Sub GridView1_HiddenEditor(sender As Object, e As System.EventArgs) Handles GridView1.HiddenEditor
        RaiseEvent HiddenMasterEditor(sender, e)
    End Sub
    Private Sub GridView1_InvalidRowException(sender As Object, e As DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs) Handles GridView1.InvalidRowException
        e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction
    End Sub
    Private Sub GridView1_ValidateRow(ByVal sender As System.Object, ByVal e As DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs) Handles GridView1.ValidateRow
        ' AL - 2011-09-16
        ' C'est dans le bonne ordre, choix de design.
        ' ProcessCurrentDetailRecord peux générer des valeur qui vont être valider par la suite
        Dim row As DataRow = CType(e.Row, DataRowView).Row
        If ValidateMasterRowEvent IsNot Nothing Then
            RaiseEvent ProcessCurrentMasterRecord(sender, e)
            RaiseEvent ValidateMasterRow(sender, e)
        Else 'Permet d'avoir un validateRow pour une grille simple sans PL - AL - 2011-11-23
            RaiseEvent ProcessCurrentMasterRecord(sender, e)
            Pl.ValidateRow(row)
        End If
        If row.HasErrors Then
            e.Valid = False
        End If
    End Sub
    Private Sub detailView_InvalidRowException(sender As Object, e As DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs) Handles DetailView.InvalidRowException
        e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction
    End Sub
    Private Sub detailView_ValidateRow(sender As Object, e As DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs) Handles DetailView.ValidateRow
        ' AL - 2011-09-16
        ' C'est dans le bonne ordre, choix de design.
        ' ProcessCurrentDetailRecord peux générer des valeur qui vont être valider par la suite
        Dim row As DataRow = CType(e.Row, DataRowView).Row
        RaiseEvent ProcessCurrentDetailRecord(sender, e, DetailViewIndex)
        RaiseEvent ValidateDetailRow(sender, e)
        If row.HasErrors Then
            e.Valid = False
        End If
    End Sub
    Private Sub GridView1_RowCellStyle(sender As Object, e As DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs) Handles GridView1.RowCellStyle
        If MasterRowCellStyleEvent IsNot Nothing Then
            RaiseEvent MasterRowCellStyle(sender, e)
        End If
    End Sub
    Private Sub DetailView_RowCellStyle(sender As Object, e As DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs) Handles DetailView.RowCellStyle
        If DetailRowCellStyleEvent IsNot Nothing Then
            RaiseEvent DetailRowCellStyle(sender, e)
        End If
    End Sub
    Private Sub GridView1_CustomColumnDisplayText(sender As Object, e As DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs) Handles GridView1.CustomColumnDisplayText
        If MasterCustomColumnDisplayTextEvent IsNot Nothing Then
            RaiseEvent MasterCustomColumnDisplayText(sender, e)
        End If
    End Sub
    Private Sub DetailView_CustomColumnDisplayText(sender As Object, e As DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs) Handles DetailView.CustomColumnDisplayText
        If DetailCustomColumnDisplayTextEvent IsNot Nothing Then
            RaiseEvent DetailCustomColumnDisplayText(sender, e)
        End If
    End Sub
    Private Sub DetailView_FocusedRowChanged(sender As Object, e As DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs) Handles DetailView.FocusedRowChanged
        Dim datarow As DataRow = DetailView.GetDataRow(e.PrevFocusedRowHandle)
        If datarow IsNot Nothing AndAlso datarow.HasErrors Then
            datarow.ClearErrors()
        End If
    End Sub
    Private Sub GridView1_FocusedRowChanged(sender As Object, e As DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs) Handles GridView1.FocusedRowChanged
        Dim datarow As DataRow = GridView1.GetDataRow(e.PrevFocusedRowHandle)
        If datarow IsNot Nothing AndAlso datarow.HasErrors Then
            datarow.ClearErrors()
        End If
    End Sub

    Private Sub DetailView_RowStyle(ByVal sender As Object, ByVal e As DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs) Handles DetailView.RowStyle
        'On change la couleur des lignes de recherche et d'ajout
        If e.RowHandle = DevExpress.XtraGrid.GridControl.AutoFilterRowHandle Then
            e.Appearance.BackColor = Color.LightGoldenrodYellow
            e.Appearance.Font = New Font(e.Appearance.Font, FontStyle.Bold)
        End If
        If e.RowHandle = DevExpress.XtraGrid.GridControl.NewItemRowHandle Then
            e.Appearance.BackColor = Color.LightGreen
            e.Appearance.ForeColor = Color.Black
        End If
        If DetailRowStyleEvent IsNot Nothing Then
            RaiseEvent DetailRowStyle(sender, e)
        End If
    End Sub
    Private Sub GridView1_RowStyle(sender As Object, e As DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs) Handles GridView1.RowStyle
        'On change la couleur des lignes de recherche et d'ajout
        If e.RowHandle = DevExpress.XtraGrid.GridControl.AutoFilterRowHandle Then
            e.Appearance.BackColor = Color.LightGoldenrodYellow
            e.Appearance.Font = New Font(e.Appearance.Font, FontStyle.Bold)
        End If
        If e.RowHandle = DevExpress.XtraGrid.GridControl.NewItemRowHandle Then
            e.Appearance.BackColor = Color.LightGreen
            e.Appearance.ForeColor = Color.Black
        End If
        If MasterRowStyleEvent IsNot Nothing Then
            RaiseEvent MasterRowStyle(sender, e)
        End If
    End Sub
    Private Sub DetailView_CustomRowCellEditForEditing(sender As Object, e As DevExpress.XtraGrid.Views.Grid.CustomRowCellEditEventArgs) Handles DetailView.CustomRowCellEditForEditing
        If DetailCustomRowCellEditForEditingEvent IsNot Nothing Then
            RaiseEvent DetailCustomRowCellEditForEditing(sender, e)
        End If
    End Sub
    Private Sub GridView1_CustomRowCellEditForEditing(sender As Object, e As DevExpress.XtraGrid.Views.Grid.CustomRowCellEditEventArgs) Handles GridView1.CustomRowCellEditForEditing
        If MasterCustomRowCellEditForEditingEvent IsNot Nothing Then
            RaiseEvent MasterCustomRowCellEditForEditing(sender, e)
        End If
    End Sub

    ''' <summary>
    ''' Used to set the look of the grid like a listBox 
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub SetListlike()
        'GridControl1
        '
        Me.GridControl1.UseEmbeddedNavigator = False
        '
        'GridView1
        '
        Me.GridView1.HorzScrollVisibility = DevExpress.XtraGrid.Views.Base.ScrollVisibility.Always
        Me.GridView1.Name = "GridView1"
        Me.GridView1.OptionsDetail.AllowExpandEmptyDetails = True
        Me.GridView1.OptionsDetail.AllowOnlyOneMasterRowExpanded = True
        Me.GridView1.OptionsDetail.EnableDetailToolTip = True
        Me.GridView1.OptionsFilter.DefaultFilterEditorView = DevExpress.XtraEditors.FilterEditorViewMode.VisualAndText
        Me.GridView1.OptionsFilter.ShowAllTableValuesInFilterPopup = True
        Me.GridView1.OptionsFilter.UseNewCustomFilterDialog = False
        Me.GridView1.OptionsFilter.AllowFilterEditor = False
        Me.GridView1.OptionsView.ShowGroupPanel = False
        Me.GridView1.OptionsSelection.MultiSelect = False
        Me.GridView1.OptionsView.ShowAutoFilterRow = True
        Me.GridView1.OptionsView.ShowChildrenInGroupPanel = True
        Me.GridView1.OptionsView.ShowFilterPanelMode = DevExpress.XtraGrid.Views.Base.ShowFilterPanelMode.Never
        Me.GridView1.OptionsView.ShowIndicator = False
        Me.GridView1.OptionsBehavior.AllowAddRows = DevExpress.Utils.DefaultBoolean.False
        Me.GridView1.OptionsView.NewItemRowPosition = NewItemRowPosition.None
    End Sub


    Private Sub GridView1_RowClick(sender As Object, e As DevExpress.XtraGrid.Views.Grid.RowClickEventArgs) Handles GridView1.RowClick
        If MasterRowClickEvent IsNot Nothing Then
            RaiseEvent MasterRowClick(sender, e)
        End If
    End Sub
    Private Sub DetailView_RowClick(sender As Object, e As DevExpress.XtraGrid.Views.Grid.RowClickEventArgs) Handles DetailView.RowClick
        If DetailRowClickEvent IsNot Nothing Then
            RaiseEvent DetailRowClick(sender, e)
        End If
    End Sub

    ''' <summary>
    ''' Shortcut key to:
    ''' CTRL-ALT-E = Export the Metaquery of the focus View
    ''' CTRL-ALT-Q = Display MetaQuery
    ''' CTRL-ALT-S = AutoSize the focus View
    ''' CTRL-S = Save Change
    ''' CTRL-R = Reload the grid without Saving
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks>GridControl Always Raise whatever the view or mode we are (View vs Editing)</remarks>
    Private Sub GridControl1_ProcessGridKey(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles GridControl1.ProcessGridKey
        Dim message As String
        Dim view As ColumnView = DirectCast(GridControl1.FocusedView, ColumnView)
        '
        If e.Control AndAlso e.Alt AndAlso e.KeyCode = Keys.Q Then
            message = String.Concat("MetaQuery: ", view.Tag.ToString, vbCrLf)
            MessageWindow.ShowMessage(message, MsgBoxStyle.Information)
            e.Handled = True
        End If
        If e.Control AndAlso e.Alt AndAlso e.KeyCode = Keys.S Then
            'view.BestFitColumns() ne s'applique pas en Layout.
        End If
        If e.Control AndAlso e.KeyCode = Keys.S Then
            Me.SaveCommand()
            e.Handled = True
        End If
        If e.Control AndAlso e.KeyCode = Keys.R Then
            Me.Reload()
            e.Handled = True
        End If
        If e.Control AndAlso e.Alt AndAlso e.KeyCode = Keys.E Then
            Using mq As MetaQuery = MetaQuery.GetMetaQueryByName(view.Tag.ToString)
                Using aFile As New System.Windows.Forms.SaveFileDialog
                    aFile.DefaultExt = "xml"
                    aFile.FileName = "MetaQuery_" + mq.QueryName
                    aFile.AutoUpgradeEnabled = True
                    If aFile.ShowDialog() = DialogResult.OK Then
                        If SystemBoxSDK.PL.MetaSDK.MetaCommand_PL.ExportMetaCommand(aFile.FileName, mq.QueryID) Then
                            MessageWindow.ShowMessage("Export Command Successful", MsgBoxStyle.Information)
                        End If
                    End If
                End Using
            End Using
            e.Handled = True
        End If
    End Sub

    Private Sub GridControl1_ViewRegistered(sender As Object, e As DevExpress.XtraGrid.ViewOperationEventArgs) Handles GridControl1.ViewRegistered
        If AfterViewRegisteredEvent IsNot Nothing Then
            RaiseEvent AfterViewRegistered(sender, e)
        Else
            If Not String.IsNullOrWhiteSpace(FormCtrlCD) Then
                Dim view As GridView
                Dim mqCtrlName As String = Nothing
                '

                view = CType(e.View, GridView)
                CType(view.DataSource, DataView).AllowNew = False
                CType(view.DataSource, DataView).AllowDelete = False
                CType(view.DataSource, DataView).AllowEdit = False
                mqCtrlName = AppManager.GetControlMqFromForm(FormCtrlCD, view.Tag.ToString)
                If Not String.IsNullOrWhiteSpace(mqCtrlName) Then
                    DetailAccess = New MetaQueryAccess(mqCtrlName)
                    CType(view.DataSource, DataView).AllowNew = DetailAccess.AllowCreate
                    CType(view.DataSource, DataView).AllowDelete = DetailAccess.AllowDelete
                    CType(view.DataSource, DataView).AllowEdit = DetailAccess.AllowUpdate

                    If Not CType(view.DataSource, DataView).AllowNew Then
                        view.OptionsView.NewItemRowPosition = NewItemRowPosition.None
                    End If
                End If
            End If
        End If
    End Sub

    Private Sub MainViewContextMenu_BeforePopup(ByVal sender As Object, ByVal e As EventArgs)
        If MainContextMenuBeforePopupEvent IsNot Nothing Then
            RaiseEvent MainContextMenuBeforePopup(sender, e)
        End If
    End Sub

    Public Sub Reload() Implements CommonExt.IReloadCommand.ReloadCommand
        ReloadGrid()
    End Sub
    ''' <summary>
    ''' Create a new row Parent Row
    ''' </summary>
    ''' <remarks>Use Interface INewCommand, So we can call it from the Ribbon button New</remarks>
    Public Sub NewCommand() Implements CommonExt.INewCommand.NewCommand
        If Me.AllowCreate Then
            GridView1.AddNewRow()
        Else
            MessageWindow.ShowMessage("You do not have rights to add new row", MsgBoxStyle.Information)
        End If
    End Sub

#Region "LayoutView "

    ''***********************************Test***Layoutview***************************************
    Protected Overridable Sub ChangeView(Grid As GridControl, node As GridLevelNode, viewName As String, removeOld As Boolean)
        Dim levelNode As GridLevelNode = node
        If levelNode Is Nothing Then
            Return
        End If
        Dim view As BaseView = Grid.CreateView(viewName)
        Grid.ViewCollection.Add(view)


        'For the current GridView
        Dim prev As BaseView = levelNode.LevelTemplate
        Dim ms As IO.MemoryStream = Nothing
        If prev IsNot Nothing Then
            ms = New IO.MemoryStream()
            prev.SaveLayoutToStream(ms, DevExpress.Utils.OptionsLayoutBase.FullLayout)
        End If

        If node.IsRootLevel Then
            prev = Grid.MainView
            Grid.MainView = view
        Else
            levelNode.LevelTemplate = view
        End If

        If ms IsNot Nothing Then
            If removeOld AndAlso prev IsNot Nothing Then
                prev.Dispose()
            End If

            ms.Seek(0, IO.SeekOrigin.Begin)
            view.RestoreLayoutFromStream(ms, DevExpress.Utils.OptionsLayoutBase.FullLayout)
            ms.Close()

            Dim mi As Reflection.MethodInfo = view.[GetType]().GetMethod("DesignerMakeColumnsVisible", Reflection.BindingFlags.InvokeMethod Or Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Instance)
            If mi IsNot Nothing Then
                mi.Invoke(view, Nothing)
            End If
            If prev IsNot Nothing Then
                AssignViewProperties(prev, view)
            End If
        End If

        If removeOld AndAlso prev IsNot Nothing Then
            prev.Dispose()
        End If
    End Sub

    Private Sub AssignViewProperties(prev As BaseView, view As BaseView)
        Dim cprev As ColumnView = TryCast(prev, ColumnView)
        Dim cview As ColumnView = TryCast(view, ColumnView)
        If cprev IsNot Nothing AndAlso cview IsNot Nothing Then
            cview.Images = cprev.Images
        End If
    End Sub

    Private Sub LayoutView_CellValueChanged(sender As Object, e As DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs) Handles LayoutView.CellValueChanged
        If MasterCellValueChangedEvent IsNot Nothing Then
            RaiseEvent MasterCellValueChanged(sender, e)
        End If
    End Sub

    Private Sub LayoutView_CustomColumnDisplayText(sender As Object, e As DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs) Handles LayoutView.CustomColumnDisplayText
        If MasterCustomColumnDisplayTextEvent IsNot Nothing Then
            RaiseEvent MasterCustomColumnDisplayText(sender, e)
        End If
    End Sub

    Private Sub LayoutView_CustomRowCellEdit(sender As Object, e As DevExpress.XtraGrid.Views.Layout.Events.LayoutViewCustomRowCellEditEventArgs) Handles LayoutView.CustomRowCellEdit

    End Sub

    Private Sub LayoutView_FocusedRowChanged(sender As Object, e As DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs) Handles LayoutView.FocusedRowChanged
        Dim datarow As DataRow = LayoutView.GetDataRow(e.PrevFocusedRowHandle)
        If datarow IsNot Nothing AndAlso datarow.HasErrors Then
            datarow.ClearErrors()
        End If
    End Sub

    Private Sub LayoutView_HiddenEditor(sender As Object, e As System.EventArgs) Handles LayoutView.HiddenEditor
        RaiseEvent HiddenDetailEditor(sender, e)
    End Sub

    Private Sub LayoutView_InitNewRow(sender As Object, e As DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs) Handles LayoutView.InitNewRow
        If InitNewMasterRowEvent Is Nothing Then
            Dim view As Views.Layout.LayoutView = CType(sender, Views.Layout.LayoutView)
            view.SetRowCellValue(e.RowHandle, view.Columns(MetaDataTable.MetaCommand.GUIDField), System.Guid.NewGuid)
        Else
            RaiseEvent InitNewMasterRow(sender, e)
        End If
    End Sub

    Private Sub LayoutView_InvalidRowException(sender As Object, e As DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs) Handles LayoutView.InvalidRowException
        e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction
    End Sub

    Private Sub LayoutView_ShownEditor(sender As Object, e As System.EventArgs) Handles LayoutView.ShownEditor
        RaiseEvent ShownMasterEditor(sender, e)
    End Sub

    Private Sub LayoutView_ValidateRow(sender As Object, e As DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs) Handles LayoutView.ValidateRow
        ' AL - 2011-09-16
        ' C'est dans le bonne ordre, choix de design.
        ' ProcessCurrentDetailRecord peux générer des valeur qui vont être valider par la suite
        Dim row As DataRow = CType(e.Row, DataRowView).Row
        If ValidateMasterRowEvent IsNot Nothing Then
            RaiseEvent ProcessCurrentMasterRecord(sender, e)
            RaiseEvent ValidateMasterRow(sender, e)
        Else 'Permet d'avoir un validateRow pour une grille simple PL - AL - 2011-11-23
            RaiseEvent ProcessCurrentMasterRecord(sender, e)
            Pl.ValidateRow(row)
        End If
        If row.HasErrors Then
            e.Valid = False
        End If
    End Sub
#End Region

End Class




